import { getAllPrimaryUrls } from '../../lib/dependency/types'
import { StringUtils } from '../../lib/utils/base/string'
import { GREASY_FORK_API_BASE_URL, MAXIM_API_URL } from '../constants/web_link'

/**
 * 字体资源类型
 */
export enum ResourceType {
  CSS = 'css',
  FONT = 'font',
  API = 'api',
}

/**
 * 资源名称
 */
export enum RESOURCE_NAME {
  NERD_FONTS_CSS = 'nerdfonts-css',
  NERD_FONTS_WOFF2 = 'nerdfonts-woff2',
  HITOKOTO = 'hitokoto',
  GREASY_FORK_API = 'greasy-fork-api',
}

/**
 * 资源标签
 */
export enum RESOURCE_TAG {
  REQUIRE = 'require',
  RESOURCE = 'resource',
  CONNECT = 'connect',
}

/**
 * 资源信息
 */
export interface ResourceInfo {
  id: RESOURCE_NAME
  url: string // 资源 URL
  type: ResourceType // 资源类型
  check?: boolean // 是否校验资源完整性
  tag?: RESOURCE_TAG // 资源标签
}

/**
 * 资源配置
 */
export const RESOURCES_CONFIG: ResourceInfo[] = [
  // Nerd Fonts CSS（https://www.nerdfonts.com/cheat-sheet）
  {
    id: RESOURCE_NAME.NERD_FONTS_CSS,
    url: `https://www.nerdfonts.com/assets/css/webfont.css#sha256-n9BaohDs9miz+Lt8pOp3hKTVji2jSbJDNSdl4wgmk6Y=`,
    type: ResourceType.CSS,
    check: true,
    tag: RESOURCE_TAG.RESOURCE,
  },
  // Nerd Fonts WOFF2
  {
    id: RESOURCE_NAME.NERD_FONTS_WOFF2,
    url: `https://www.nerdfonts.com/assets/fonts/Symbols-2048-em%20Nerd%20Font%20Complete.woff2`,
    type: ResourceType.FONT,
    check: false,
    tag: RESOURCE_TAG.RESOURCE,
  },
  // 一言
  {
    id: RESOURCE_NAME.HITOKOTO,
    url: new URL(MAXIM_API_URL).host.toString(),
    type: ResourceType.CSS,
    check: false,
    tag: RESOURCE_TAG.CONNECT,
  },
  // 油叉
  {
    id: RESOURCE_NAME.GREASY_FORK_API,
    url: new URL(GREASY_FORK_API_BASE_URL).host.toString(),
    type: ResourceType.API,
    check: false,
    tag: RESOURCE_TAG.CONNECT,
  },
]

/**
 * 获取所有依赖 URL
 */
export function getAllRequires(): string[] {
  return getAllPrimaryUrls()
}

/**
 * 获取所有 resource 资源 URL
 */
export function getAllResources(): Record<string, string> {
  return Object.fromEntries(RESOURCES_CONFIG.filter(font => font.tag === RESOURCE_TAG.RESOURCE).map(font => [font.id, font.url]))
}

/**
 * 获取所有 connect 资源 URL
 */
export function getAllConnects(): string[] {
  const urls = RESOURCES_CONFIG
    .filter(font => font.tag === RESOURCE_TAG.CONNECT)
    .map(font => font.url)

  return StringUtils.addToArrayWithDeduplication(urls, '*')
}
